package com.hanbit.startup;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.hanbit.member.model.Member;
import com.hanbit.member.service.MemberService;


@Controller
public class MainController {
	
	@Autowired
	private MemberService service;
	
	@RequestMapping("/")
	public String hello(){
		return "front/main";
	}
	
	@RequestMapping("/admin.do")
	public String admin(){
		return "admin/index";
	}
	
	@RequestMapping("/name.do")
	public String getName(){
		return "front/getName";
	}
	@RequestMapping("/main.do")
	public String goMain(){
		return "front/main";
	}
	@RequestMapping("/info.do")
	public String goInfo(HttpServletRequest request){
		String content = request.getParameter("content");
		return "front/info/"+content;
	}
	@RequestMapping("/member.do")
	public String goMember(HttpServletRequest request){
		String content = request.getParameter("content");
		return "front/member/"+content;
	}
	@RequestMapping("/join.do")
	public String goJoin(HttpServletRequest request){
		return "front/member/registration";
	}
	@RequestMapping("/join.action")
	public ModelAndView joinAction(@ModelAttribute("Member")Member member){
		ModelAndView mav = new ModelAndView();
		System.out.println(member);
		service.addMember(member);
		mav.addObject("member",member);
		mav.setViewName("front/main");
		return mav;
	}
	
	@RequestMapping(value="/login.do")
	public String loginAction(HttpServletRequest request,HttpSession session,Model model){
		String id = request.getParameter("id");
		String passwd = request.getParameter("passwd");
		
		Member member=service.getMember(id);
		if(member==null){return "front/member/loginAction";}
		if(member.getPasswd().equals(passwd)){
			session.setAttribute("sMember",member);
			model.addAttribute("member",member);
		}
		return "front/member/loginAction";
		
	}
	@RequestMapping(value="/logout.do")
	public String logout(HttpSession session){
		session.invalidate();
		return "redirect:main.do";
	}
	@RequestMapping(value="/updateMember.action")
	public String updateMember(@ModelAttribute("Member")Member member,Model model,HttpSession session){
		service.updateMember(member);
		model.addAttribute("member",member);
		session.setAttribute("sMember",member);
		return "redirect:main.do";
	}
}
